#ifndef BASE_MODUL_H
#define BASE_MODUL_H
#include <QFile>
#include <QtCore> 
#include <QTextCodec>
#include <QCoreApplication>
#include <QDomDocument>
#include <QtDebug>
#include <QDebug> 
#include <QSettings>
#include <QDomDocument>
#include <QDomElement>
#include <QDomImplementation>
#include <QDomProcessingInstruction>
#include <QFile>
#include <QTextCodec>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QCalendarWidget>
#include <QtGui/QDialog>
#include <QTextTable>
#include <QInputDialog>
#include <QMenu>
#include <QString>
#include <QtDebug>
#include <QDebug> 
#include <QDesktopServices>
#include <QDebug>
#include <QString>
#include <QMap>
#include <QList>
#include <QStringList>
#include <QObject>
#include <QDateTime>
#include <QDate>
#include <QImageReader>
#include <QPixmap>
#include <QSettings>
#include <QTimer>
#include <QProgressDialog>
#include <QPainter>
#include <QPixmap>
#include <QUrl>
#include <QColorDialog>
#include <QFileDialog>
#include <QMessageBox>
#include <QWorkspace>
#include <QDockWidget>
#include <QTcpSocket>
#include <QString>
#include <QDebug>
#include <QObject>
#include <QFileInfo>
#include <QObject>
#include <QHttp>
#include <QFile>
#include <QBuffer> 
#include <QTcpSocket>
#include <QString>
#include <QTextStream>
#include <QDebug>
#include <QMessageBox>
#include <QAbstractSocket>
#include <QDateTime>
#include <QDate>
#include <QLocale>
#include <QObject>
#include <QFileInfo>
#include <QObject>
#include <QHttp>
#include <QFile>
#include <QBuffer>
#include <QTextCursor>
#include "bestqtidy.h"
#include "config.h"
#include <QTextDocument>

#define POINT_TO_CM(pta) ((pta)/28.3465058)


/* limit Transbonder Date: Mon, 1 Jan 2007 01:00:04 */
#define _UNIXTIME_LIMIT_ 1167609604
#define _DIFFNULL_ 4

#define _SCHWARZ_ "#000000"
#define _WEISS_ "#ffffff"


typedef QMap<QString, QString> Appsetting; 
typedef QMap<int, QStringList> resultMap;
typedef QMap<QString, QString> Vario;
typedef QMap<QString, QString> sqlr;
typedef QList<QStringList> rowList;



#define _PROGRAM_NAME_ "HTML Editor Pulitzer PC"
#define _PROGRAM_NAME_DOMAINE_ "ciz.ch"
#define _ORGANIZATION_NAME_ "PPK-Screendesign/Webprogramm"
#define _PROGRAM_VCMS_ "version 2.0.8"
#define _PROGRAM_TITLE_  _PROGRAM_NAME_" - "_PROGRAM_VCMS_
#define Q_WORKS_PEND "open"
#define _PROGRAM_SHORT_NAME_ "edit_xhtml_0"

#if defined Q_WS_MAC
#define WEBAGENTNAME "Mac FinderRobots / PPK_W @ciz.ch"
#endif
#if defined Q_WS_WIN
#define WEBAGENTNAME "Windows FinderRobots QT4.2 / PPK_W @ciz.ch"
#endif
#if defined Q_WS_X11
#define WEBAGENTNAME "Unix FinderRobots QT4.2  / PPK_W @ciz.ch"
#endif

////////////////////////////// homePath()  currentPath()

/* read the contenet of a local file as qstring */
extern inline QString DDopen(QString fullFileName)
{
    QString inside = "";
    QFile file(fullFileName); 
    if (file.exists()) {
                if (file.open(QFile::ReadOnly | QFile::Text)) {
                    inside = QString::fromUtf8(file.readAll());
                  file.close();
                }
    }

return inside;
}


#define NO_TEXT_FILE_PAGE \
              QString( DDopen(QString::fromUtf8(":/img/_notext.html")) )

#define WORK_CACHEDIR \
              QString( "%1/.%2/" ).arg( QDir::homePath(), _PROGRAM_SHORT_NAME_ )
#define APPLICATIONCACHEDIR \
               QString( "%1" ).arg(WORK_CACHEDIR) 
#define HOME_DIR_YOUR \
              QString( "%1/" ).arg( QDir::homePath())
              
#define IMGDIRTMP \
               QString( "%1IMG/" ).arg( WORK_CACHEDIR )
               
#define IMAGE_PASTE_CACHE \
               QString( "%1IMGP/" ).arg( WORK_CACHEDIR )           
               
               
               
               
               
               
#define USERNOTEHTML \
               QString( "%1user.html" ).arg( IMGDIRTMP )
       
#define REQUESTSTREAM \
               QString( "%1._up.xml" ).arg( WORK_CACHEDIR )
#define MOVESTREAM \
               QString( "%1._move.xml" ).arg( WORK_CACHEDIR )
#define GETSTSTREAM \
               QString( "%1._down.xml" ).arg( WORK_CACHEDIR ) 
#define LASTACTIONB \
               QString( "%1._last_davinfo.xml" ).arg( WORK_CACHEDIR ) 
#define LASTMOVEACTION \
               QString( "%1._last_move.xml" ).arg( WORK_CACHEDIR ) 
#define LASTACTIONPUT \
               QString( "%1._last_put.xml" ).arg( WORK_CACHEDIR ) 
               
#define APPLICATION_SETTING\
               QString( "%1.SettingAll.xml" ).arg( WORK_CACHEDIR ) 
               
#define WORDLISTCOMPLETE\
               QString( "%1.WordList.dat" ).arg( WORK_CACHEDIR ) 
               
#define SQLLOG_CACHEDIR \
              QString( "%1/sql_log/" ).arg( WORK_CACHEDIR )
#define PERMANENT_ERROR_LOG_FILE \
              QString( "%1/_session_sql_error.txt" ).arg( WORK_CACHEDIR )
              
              
              
#define APPLICATIONTMP \
               QString( "%1tmpunpack/" ).arg(WORK_CACHEDIR) 
              

//
/*  Save file as base_modul.h  */
/*  incomming class name Base_Modul */
//
//

#define KEYWORDMAX_NUMMER 200


/* zip libs  ###### start ###################################################################*/
#include "zlib.h"
#include <stdio.h>
#include "quazip.h"
#include "quazipfile.h"
#include <QTextCodec>


#ifdef STDC
#  include <string.h>
#  include <stdlib.h>
#endif

#ifdef USE_MMAP
#  include <sys/types.h>
#  include <sys/mman.h>
#  include <sys/stat.h>
#endif

#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__)
#  include <fcntl.h>
#  include <io.h>
#  define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY)
#else
#  define SET_BINARY_MODE(file)
#endif

#ifdef VMS
#  define unlink delete
#  define GZ_SUFFIX "-gz"
#endif
#ifdef RISCOS
#  define unlink remove
#  define GZ_SUFFIX "-gz"
#  define fileno(file) file->__file
#endif
#if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
#  include <unix.h> /* for fileno */
#endif


#ifndef GZ_SUFFIX
#  define GZ_SUFFIX ".gz"
#endif
#define SUFFIX_LEN (sizeof(GZ_SUFFIX)-1)

#define BUFLEN      16384
#define MAX_NAME_LEN 1024

#ifdef MAXSEG_64K
#  define local static
   /* Needed for systems with limitation on stack size. */
#else
#  define local
#endif

#include <iostream>
#include <stdio.h>

using namespace std;


extern inline QString  BiteorMega( int peso  )
{
    QString humanread;
    qreal  faktor = 1024.00;

    qreal bytesizefile = peso / faktor;
    int kilo = 0;
    
    if (bytesizefile > 0) {
        if (bytesizefile < 1) {
           kilo = 1; 
        } else {
           kilo = bytesizefile;
        }
    }
    
   if (kilo < 1025) {
   humanread = QString("Kb.%1").arg(kilo);
   return humanread;
   }
   
   qreal megad = bytesizefile / faktor;
   
   if (megad < 1025) {
   humanread = QString("MB.%1").arg(megad, 0, 'f', 2);
   return humanread;
   } else {
            qreal gigab = megad / faktor;
            humanread = QString("GB.%1").arg(gigab, 0, 'f', 2);
       
       
   }
   
return humanread;
}



class PackZip : public QObject
{
    Q_OBJECT
    
public:
PackZip()
{
startnow = QDir::currentPath();
} 
~PackZip()
{
QDir::setCurrent(startnow);
}
void SetJob( const QString packfolder , const QString zipoutfolder )
{
    
  startdir = packfolder;   /* grab all this file */
  zipdir = zipoutfolder;   /* save zip to this dir */
  startnow = QDir::currentPath();
  Init();
}

private:
void Init()
{
    canmake = false;
    if (!zipdir.contains("/")) {
        ResetDir();
        return;
    }
    if (!zipdir.endsWith("/")) {
        ResetDir();
       return; 
    }
    if (!startdir.contains("/")) {
        ResetDir();
        return;
    }
    if (!startdir.endsWith("/")) {
       ResetDir();
       return; 
    }
    canmake = true;
    QDir dir(startdir);
    char c;
    char* suk;
    qreal cento;
    qreal percentuale;
    QString dirname = dir.dirName();
    selfname = dirname + ".zip";
    zipfile = zipdir;
    zipfile.append(dirname);
    zipfile.append(".zip");
    
    QFile zcheck(zipfile);
     if (zcheck.exists()) {
      zcheck.remove();
     }
    
    dirandfile.clear();
    IndexDir(startdir);
    if (dirandfile.size() > 0) {
        
      QuaZip zip(zipfile);
      if(!zip.open(QuaZip::mdCreate)) {
      ResetDir();
      return;
      }
      
      QuaZipFile outFile(&zip);
      
      int totalf = dirandfile.size();
      
       ///////qDebug() << "### totalfile " <<  dirandfile.size();
         for (int i = 0; i < dirandfile.size(); ++i) {
             QString filepak = dirandfile.at(i);
             const  QString abse = filepak;
             const  QString goname = filepak.replace(startdir,"");
             
             QFile inFile(abse);
                   inFile.setFileName(abse);
             
             if(!inFile.open(QIODevice::ReadOnly)) {
              ResetDir();
              return;
             }
             
              if(!outFile.open(QIODevice::WriteOnly, QuaZipNewInfo(goname, inFile.fileName()))) {
              ResetDir();
              return;
              }
              
               while(inFile.getChar(&c)&&outFile.putChar(c));
                if(outFile.getZipError()!=UNZ_OK) {
                  ResetDir();
                  return;
                }
                
                outFile.close();
                if(outFile.getZipError()!=UNZ_OK) {
                ResetDir();
                return;
                }
                inFile.close();
                cento = 100;
                percentuale = i*cento/totalf;
                int status = percentuale;
                emit Status(status);
                
                
                QString fileqinfo = goname;
                        fileqinfo.append(" ");
                        fileqinfo.append(BiteorMega(inFile.size()));
                QByteArray fe = fileqinfo.toAscii();
                suk = fe.data();
                
                            ////////// cout <<  "Status. " << percentuale << "% " << suk << "\n";
                             /////fflush ( stdin );
             
             ////////qDebug() << "### status " <<  status;
             //////////qDebug() << "### d " <<  goname;
         }
        
          zip.close();
          if(zip.getZipError()!=0) {
          QDir::setCurrent(startnow);
          }
          
          
          
          
          QFile re(zipfile);
          
           QString fr = re.fileName();
                        fr.append(" ");
                        fr.append(BiteorMega(re.size()));
          
          QByteArray fe = fr.toAscii();
                suk = fe.data();
          
         ///////////////// cout <<  "End file " << suk << "\n";
          ///////qDebug() << "### status 100";
          emit Status(100);
          emit ZipEnd(zipfile);
          return;
          /////////////qDebug() << "### emitend " <<  zipfile;
    }
emit ZipError();
}
void ResetDir()
{
    emit ZipError();
    QDir::setCurrent(startnow);
}
void IndexDir(const QString d)
{
   QDir dir(d);
   if (dir.exists())
   {
      const QFileInfoList list = dir.entryInfoList();
      QFileInfo fi;
      for (int l = 0; l < list.size(); l++)
      {
         fi = list.at(l);
         if (fi.isDir() && fi.fileName() != "." && fi.fileName() != "..") {
            IndexDir(fi.absoluteFilePath());
         } else if (fi.isFile() && fi.fileName() != selfname ) {
            dirandfile.append(fi.absoluteFilePath());
         } 
        
      }
   }
}
    QString startnow;
    QStringList dirandfile;
    QString startdir;
    QString zipdir;
    QString zipfile;
    QString selfname;
    bool canmake;
signals:
    void ZipEnd( QString fileresult );
    void ZipError();
    void Status(int o );
public slots:

};





extern inline void gz_compress( FILE   *in , gzFile out ) 
{
    local char buf[BUFLEN];
    int len;
    int err;
    
    for (;;) {
        len = (int)fread(buf, 1, sizeof(buf), in);
        if (ferror(in)) {
            perror("fread");
            exit(1);
        }
        if (len == 0) break;

        if (gzwrite(out, buf, (unsigned)len) != len) {
         return;   
        }
    }
    fclose(in);
    if (gzclose(out) != Z_OK) {
     return;
    }
}


static inline bool  OpenZip( const QString zipfile, const QString outputdir )
{
    ///////////// const QString cartella = QDir::currentPath();
     /////////qDebug() << "### from unzzip function path " <<  QDir::currentPath();
   /////////// qDebug() << "### outputdir " <<  outputdir;
    //////////qDebug() << "### zipfile " <<  zipfile;
    char* suk;
    QuaZip zip(zipfile);
    bool extractsuccess = false;
    zip.open(QuaZip::mdUnzip);
    QuaZipFile file(&zip);
       for(bool more=zip.goToFirstFile(); more; more=zip.goToNextFile()) {
           file.open(QIODevice::ReadOnly);
           QString name = zip.getCurrentFileName();
                   name.prepend(outputdir);   /* extract to path ....... */
           QFile meminfo(name);
           QFileInfo infofile(meminfo);
           QDir dira(infofile.absolutePath());
           if ( dira.mkpath(infofile.absolutePath()) ) { 
           /* dir is exist*/
           /////////qDebug() << "### name  " << name;     
           /////qDebug() << "### namedir yes  " << infofile.absolutePath();
               
               
               
               QString fileqinfo = zip.getCurrentFileName();
                QByteArray fe = fileqinfo.toAscii();
                suk = fe.data();
                
                //////////////////cout <<  "Processing..... " << suk << "\n";
               
               
               
               if ( meminfo.open(QIODevice::ReadWrite) ) {
               meminfo.write(file.readAll());   /* write */
               meminfo.close();
               extractsuccess = true;
               //////////RegisterImage(name);
               }
           } else {
             file.close();
             return false;               
           }
           file.close(); // do not forget to close!
        }
    zip.close();
    
return extractsuccess;
}




extern inline bool  MakeGzipOneFile( QString filelocation )
{
    local char outfile[MAX_NAME_LEN];
    FILE  *in;
    gzFile out;
    QByteArray cgofile = filelocation.toAscii();
    char* file = cgofile.data();
    QString const busgo = filelocation.append(GZ_SUFFIX);
    strcpy(outfile, file);
    strcat(outfile, GZ_SUFFIX);   /* attach suffix */
    in = fopen(file, "rb");
    
    if (in == NULL) {
     return false;
    }
    out = gzopen(outfile,"wb6");
    if (out == NULL) {
      fclose( in );
      return false;
    }
    gz_compress(in, out);
    
    QFile f( busgo );
    return f.exists(busgo);
}



extern inline QString  OpenGzipOneFile( QString fileName )
{
    QString inside = "";
     gzFile file;
      file = gzopen (fileName.toUtf8().data(), "rb");
      if(!file) {
        QMessageBox::critical(0, "Error",QString("Can't open file %1").arg(fileName));
        return inside;
      }
      QByteArray input;
      char buffer[1024];
      QByteArray inputData;
      while(int readBytes =  gzread (file, buffer, 1024))
       {
        input.append(QByteArray(buffer, readBytes));
      }
      gzclose(file);
      
      inside = QString::fromUtf8(input.data());
      return inside;
}









/* zip libs  ###### stop ###################################################################*/
















class Base_Modul
{

//
public: 
Base_Modul()
{
 Load_Connector();
}
/* grep nummer on [77] */
QString  Firstupper( QString nametomake )
{
    QString firtupper,lower,fullname,na,nb;
    int xse = nametomake.size();
    na = nametomake.toLower();
    nb = nametomake.toUpper();
    firtupper = nb.left(1);
    fullname = QString("%1%2").arg(firtupper).arg(na.mid(1,xse - 1));
    
return fullname;
}

bool  image_extension( QString nametomake )
{
    bool fanny = false;
    QString na;
    na = nametomake.toLower();
    if ( na.endsWith(".png") or na.endsWith(".jpeg") or na.endsWith(".jpg") or na.endsWith(".gif") ) {
     fanny = true;   
    }
return fanny;
}

bool file_put_contents_append(QString fullFileName,QString xml)
{
    QString data = xml+"\n";
    QFile f( fullFileName );
	if ( f.open( QFile::Append | QFile::Text ) )
	{
		QTextStream sw( &f );
		sw << data;
		f.close();
		return true;
	}
	return false;
    
}





const char*  Rotate( int casir )
{
    const char *bane;
    
    switch(casir)
                {
                case 1:
                bane ="-";
                break;
                case 2:
                bane ="\\";
                break;
                case 3:
                bane ="|";
                break;
                case 4:
                bane ="/";
                break;
                
    }
    
return bane;
}



QString DesktopFile( QString fullFileName )
{
    if (fullFileName.startsWith("http://", Qt::CaseInsensitive) or 
        fullFileName.startsWith("https://", Qt::CaseInsensitive) or
        fullFileName.startsWith("ftp://", Qt::CaseInsensitive) or
        fullFileName.startsWith("news://", Qt::CaseInsensitive) or
        fullFileName.startsWith("mailto:", Qt::CaseInsensitive) or
        fullFileName.startsWith("webdav://", Qt::CaseInsensitive)  )
       { 
         return fullFileName;
       } else {
         return fullFileName.prepend("file:///");  
       }
}

/* encode to url strings */
QString EncodeUrlPart( QString xml  )
{
    QUrl urlmod(QString("http://localhost/%1").arg(xml));
    QByteArray capsed(urlmod.toEncoded());
    QString res = QString("%1").arg(capsed.data());
    res = res.replace("%20","_");
    res = res.replace("%","");
    QUrl urlmod2(res);
    res = urlmod2.path ();
    res = res.replace("/","");
    return res;
}


/* time null unix time long nummer */
uint QTime_Null()
{
    QDateTime timer1( QDateTime::currentDateTime() ); 
    return timer1.toTime_t();
}

/* display a mail date format  UmanTimeFromUnix(QTime_Null())   */
QString UmanTimeFromUnix( uint unixtime )
{
     /* mail rtf Date format! http://www.faqs.org/rfcs/rfc788.html */
     QDateTime fromunix;
     fromunix.setTime_t(unixtime); 
     QStringList RTFdays = QStringList() << "day_NULL" << "Mon" << "Tue" << "Wed" << "Thu" << "Fri" << "Sat" << "Sun";
     QStringList RTFmonth = QStringList() << "month_NULL" << "Jan" << "Feb" << "Mar" << "Apr" << "May" << "Jun" << "Jul" << "Aug" << "Sep" << "Oct" << "Nov" << "Dec";
     QDate timeroad(dateswap("yyyy",unixtime),dateswap("M",unixtime),dateswap("d",unixtime));
     /*qDebug() << "### RTFdays " << RTFdays.at(timeroad.dayOfWeek());
     qDebug() << "### RTFmonth " << RTFmonth.at(dateswap("M",unixtime));
     qDebug() << "### yyyy " << dateswap("yyyy",unixtime);
     qDebug() << "### M " << dateswap("M",unixtime);
     qDebug() << "### d " << dateswap("d",unixtime);*/
     QStringList rtfd_line;
     rtfd_line.clear();
     rtfd_line.append("Date: ");
     rtfd_line.append(RTFdays.at(timeroad.dayOfWeek()));
     rtfd_line.append(", ");
     rtfd_line.append(QString::number(dateswap("d",unixtime)));
     rtfd_line.append(" ");
     rtfd_line.append(RTFmonth.at(dateswap("M",unixtime)));
     rtfd_line.append(" ");
     rtfd_line.append(QString::number(dateswap("yyyy",unixtime)));
     rtfd_line.append(" ");
     rtfd_line.append(fromunix.toString("hh:mm:ss"));
     rtfd_line.append("");
     /*qDebug() << "### mail rtf Date format " << rtfd_line.join("");*/
return QString(rtfd_line.join(""));
}
/* date format to stirng */
QString datetr(QString form, uint unixtime )
{
     QDateTime fromunix;
     fromunix.setTime_t(unixtime); 
     return fromunix.toString((const QString)form);
}
/* take a qstring and put to double */
double direct_double(QString xid)
{
    double newnummer = 0.01;
    if (is_numeric(xid)) {
        bool ok; 
        newnummer = xid.toDouble(&ok);
        return newnummer;
    }
 return newnummer;
}

/* take a qstring and put to int */
int direct_int(QString xid)
{
    int newnummer = 0;
    if (is_numeric(xid)) {
        bool ok; 
        newnummer = xid.toInt(&ok);
        return newnummer;
    }
 return newnummer;
}

/* return int value from a unixtime date MMM YYY ... */
int dateswap(QString form, uint unixtime )
{
     QDateTime fromunix;
     fromunix.setTime_t(unixtime); 
     QString numeric = fromunix.toString((const QString)form);
     bool ok; 
     return (int)numeric.toFloat(&ok);
}


/* check if a int or float nummer */
bool is_numeric(QString incomming)
{
    incomming.replace(QString(" "), QString("")); /* trimm */
    QString str2 = incomming;
    bool ok; 
    str2.toFloat(&ok); 
return ok;
}

/* encode to name */
QString encodeBase64( QString xml )
{
    QByteArray text;
    text.append(xml);
    return text.toBase64();
}

/* decode to name */
QString decodeBase64( QString xml )
{
    QByteArray xcode("");;
    xcode.append(xml);
    QByteArray precode(QByteArray::fromBase64(xcode));
    QString notetxt = precode.data();
    return notetxt;
}
/* extract domaine from a url */
QString Domain( QString url )
{
   QString hdomain = "";
   QUrl wurl( url );
   hdomain = QString( "http://%1/" ).arg( wurl.host() );
   return hdomain;
}
/* return a config setting from a xml file */
QString  Global_Config_Base( QString tagname , QString filename )
{
    QFile xmlfile(filename);
    QString isis="";
    if(!xmlfile.open( QIODevice::ReadOnly ) ) {
    return isis;
    }
    QString errorStr, obname, inhalt;
    int errorLine;
    int errorColumn;
    
    QDomDocument doc("http://www.pulitzer.ch/2005/PuliCMS/1.0"); 
     if (!doc.setContent(&xmlfile,true, &errorStr, &errorLine, &errorColumn)) {
     return isis;
     xmlfile.close();
     } 
    QDomElement root = doc.documentElement();
    QDomNode n = root.firstChild();
    while( !n.isNull() )
    {
        QDomElement e = n.toElement();
        if( !e.isNull() )
        {
                   if( e.tagName() == tagname ) {
                   xmlfile.close();
                   return decodeBase64(e.text());
                   }
                   
         n = n.nextSibling();
        } 
    }
xmlfile.close();
return isis;
}

/* read the contenet of a local file as qstring */
QString fopenutf8(QString fullFileName)
{
    QString inside = "";
    QFile file(fullFileName); 
    if (file.exists()) {
                if (file.open(QFile::ReadOnly | QFile::Text)) {
                    inside = QString::fromUtf8(file.readAll());
                  file.close();
                }
    }

return inside;
}


/* read the contenet of a local file as qstring */
QString fopeniso(QString fullFileName)
{
    QString inside = "";
    QFile file(fullFileName); 
    if (file.exists()) {
                if (file.open(QFile::ReadOnly | QFile::Text)) {
                    inside =file.readAll();   
                  file.close();
                }
    }

return inside;
}

/* write a file to utf-8 format */
bool fwriteutf8(QString fullFileName,QString xml)
{
    if (fullFileName.contains("/", Qt::CaseInsensitive)) {
    QString ultimacartellaaperta = fullFileName.left(fullFileName.lastIndexOf("/"))+"/";
    QDir dira(ultimacartellaaperta);
    if ( dira.mkpath(ultimacartellaaperta) ) { } else {
    return false;
    }
    }
    
        QTextCodec *codecx;
        codecx = QTextCodec::codecForMib(106);
        QFile f( fullFileName );
        if ( f.open( QFile::WriteOnly | QFile::Text ) )
        {
        QTextStream sw( &f );
        sw.setCodec(codecx);
        sw << xml;
        f.close();
        return true;
        }
        return false;
}

/* write a file to iso format */
bool fwriteiso(QString fullFileName,QString xml)
{
    
    if (fullFileName.contains("/", Qt::CaseInsensitive)) {
    
    QString ultimacartellaaperta = fullFileName.left(fullFileName.lastIndexOf("/"))+"/";
    QDir dira(ultimacartellaaperta);
    if ( dira.mkpath(ultimacartellaaperta) ) { } else {
    return false;
    }
    
    }
    
    
        QTextCodec *codecx;
        codecx = QTextCodec::codecForMib(4);
        QFile f( fullFileName );
        if ( f.open( QFile::WriteOnly | QFile::Text ) )
        {
        QTextStream sw( &f );
        sw.setCodec(codecx);
        sw << xml;
        f.close();
        return true;
        }
        return false;
}


/* check if a file exist alert dons say true if a zero byte file!  */
bool is_file(QString fullFileName)
{
    if (!fullFileName.size() > 3) {
      return false;  
    }
    QFile f( fullFileName );
	if ( f.exists(fullFileName) ) {
    return true;  
	} else {
	return false;
    }
}

/* remove a file */
bool qt_unlink(QString fullFileName)
{
    if (fullFileName.size() > 0) {
    QFile f( fullFileName );
	if ( f.exists(fullFileName) ) {
       if (f.remove()) {
        return true;
       }
	}
    }
return false;
}

/* copy file from a to b ... if dir not exist make it ...*/
bool Copy_To(QString inputfile, QString outfile)
{
    bool actioncpy = false;
    QString ultimacartellaaperta = outfile.left(outfile.lastIndexOf("/"))+"/";
    QDir dira(ultimacartellaaperta);
    if ( dira.mkpath(ultimacartellaaperta) ) { } else {
    return actioncpy;
    }
    if (is_file(inputfile)) {
           qt_unlink(outfile);
           QFile Imaged(inputfile); 
               if (Imaged.copy(outfile)) {
                   actioncpy = true; 
                }
    }
return actioncpy;
}




/* quote and dequote sql s result */
QString sql_Quote( QString xml )
{
   //the following checks are necessary before exporting
  //strings to XML. see http://hdf.ncsa.uiuc.edu/HDF5/XML/xml_escape_chars.html for details
   QString text = xml;
   text.replace("\"","\\\"");  /* 228 ``*/
   text.replace("'","`");
   return text;
}

QString sql_DeQuote( QString xml )
{
   //the following checks are necessary before exporting
  //strings to XML. see http://hdf.ncsa.uiuc.edu/HDF5/XML/xml_escape_chars.html for details
  QString text = xml;
   text.replace("\\\"","\"");  /* 228 ``*/
   text.replace("`","\'");
  return text;
}








/* decode url from cookie or other */
QString  Url_Decode( QString indata )
{
/*
http://www.blooberry.com/indexdot/html/topics/urlencoding.htm
Dollar ("$")  24 
Ampersand ("&") 26
Plus ("+") 2B
Comma (",")  2C
Forward slash/Virgule ("/") 2F
Colon (":")  3A
Semi-colon (";") 3B
Equals ("=") 3D
Question mark ("?") 3F
'At' symbol ("@")  40
Left Curly Brace ("{")  7B
Right Curly Brace ("}") 7D
Vertical Bar/Pipe ("|") 7C
Backslash ("\") 5C
Caret ("^") 5E
Tilde ("~") 7E
Left Square Bracket ("[") 5B
Right Square Bracket ("]") 5D
Grave Accent ("`")  60
*/
QString blnull = "";
QString notaccept = "%60|%5D|%5B|%7E|%5E|%5C|%7C|%7D|%7B";
QStringList notallow;
            notallow = notaccept.split("|");

             for (int i = 0; i < notallow.size(); ++i) {
                 if ( indata.contains(notallow.at(i)) ) {
                   return blnull;   
                 } 
             }
  
         QString spaceout = indata.replace("%20"," ");
                 spaceout = spaceout.replace("%3A",":");  
                 spaceout = spaceout.replace("%3B",";");
                 spaceout = spaceout.replace("%3D","=");
                 spaceout = spaceout.replace("%2F","/");
                 spaceout = spaceout.replace("%3F","?");
                 spaceout = spaceout.replace("%40","@");
                 spaceout = spaceout.replace("%24","$");
                 spaceout = spaceout.replace("%2B","+");
                 spaceout = spaceout.replace("+"," ");  
                 int zool = spaceout.indexOf(";",0);
         return spaceout.left(zool);;
}


/* grep nummer on [77] */
int  BraketNummer( QString braket )
{
    int esanummer = 0;
    if (braket.startsWith("[")) {
       braket.replace(QString("["), QString("")); 
       int zool = braket.indexOf("]",0); 
           if (zool > 0) {
              QString   xid = braket.left(zool);  
               if (is_numeric(xid)) {
                      bool ok; 
                      esanummer = xid.toInt(&ok);
               }
           }
    }
return esanummer;
}

/* remove dir recursive */
void DownDir_RM(const QString d)
{
   QDir dir(d);
   //////SqlLog("order to delete dir:"+d+" ");
   if (dir.exists())
   {
      const QFileInfoList list = dir.entryInfoList();
      QFileInfo fi;
      for (int l = 0; l < list.size(); l++)
      {
         fi = list.at(l);
         if (fi.isDir() && fi.fileName() != "." && fi.fileName() != "..")
            DownDir_RM(fi.absoluteFilePath());
         else if (fi.isFile())
         {
            qt_unlink(fi.absoluteFilePath());
            ///////if (!ret) {
               ////////SqlLog("Can't remove: " + fi.absoluteFilePath() + " (write-protect?)");
         } 
        
      }
     /////// SqlLog("Remove: " + d + " ");
      dir.rmdir(d);
      
   }
} 


QString FileNameFix( QString xml )
{
   //the following checks are necessary before exporting
  //strings to XML. see http://hdf.ncsa.uiuc.edu/HDF5/XML/xml_escape_chars.html for details
  QString text = xml;
   text.replace("\\\"","");  /* 228 ``*/
   text.replace("`","");
   text.replace(" ","_");
  return text;
}


QString CheckSlash( QString path )
{
    if (path == "/") {
     return path;
    }
    QString cleanpath;
    if (!path.startsWith("/")) {
        path = path.prepend("/");
     }
    if (!path.endsWith("/")) {
       path = path.append("/");
    }
    cleanpath = path;
    cleanpath = cleanpath.replace("//","/");
    return cleanpath;
}



/* simple md5 to found diffs */
QString myMd5( QString xml )
{
    QString str = xml;
    str.resize(38);
    QString upperd = str.toUpper();
    QByteArray text;
    text.append(upperd);
    QString parse = text.toBase64();
    parse.resize(12);
    QString md7 = parse;
    return md7;
}
void ResetDir()
{
    QDir::setCurrent(currentdir); 
}
uint MailTimeString( QString indate )
{
    /* incomming format Wed, 07 Feb 2007 18:44:19 GMT*/
    /* or mail rtf Date format! http://www.faqs.org/rfcs/rfc788.html */
    indate.replace("Date:","");
    indate.trimmed();
    QStringList sdate = indate.split(" ");
    if (sdate.size() != 6) {
    return QTime_Null();
    }
    sdate.removeFirst();
    sdate.removeLast();
    QString reformat = sdate.join(" ");
    QDateTime dateTime2 = QDateTime::fromString(reformat,"dd MMM yyyy HH:mm:ss");
    dateTime2.setTimeSpec(Qt::UTC);
    QDateTime dateTime3 = dateTime2.toLocalTime();
    return dateTime3.toTime_t();
}

 QStringList ReverseList(const QStringList &list)
{
    QStringList reversedList = list;
    QStringList::iterator __first = reversedList.begin();
    QStringList::iterator __last = reversedList.end();
    {
        while (true)
            if (__first == __last || __first == --__last)
                return reversedList;
            else
            {
                qSwap(*__first, *__last);
                ++__first;
            }
    }
    
}
uint DavTimeStringCreated( QString indate )
{
    /* incomming format "2007-02-07T18:44:24Z" */
           indate.resize(indate.size() - 1);
	       QStringList sdate = indate.split("T");
           if (sdate.size() != 2) {
           return QTime_Null();
           }
           QString reformat = sdate.join(" ");
           //////qDebug() << "date  converted " << reformat;
           QDateTime dateTime2 = QDateTime::fromString(reformat,"yyyy-MM-dd HH:mm:ss");
	    dateTime2.setTimeSpec(Qt::UTC);
           QDateTime dateTime3 = dateTime2.toLocalTime();
    return dateTime3.toTime_t();
}
QString CDDirUp( QString path )
{
     /* linux cd..  */
    if (path == "/") {
     return path;
    }
    QStringList list;
    list = path.split("/");
    QStringList fdir;
    int totaldir = list.size() - 2; 
    ////////qDebug() << "#### cd .. ->" << totaldir << "-" << list.size() << "-" << list;
    fdir.clear();
    for (int i = 0; i < totaldir; ++i)  {
        fdir.append(list.at(i));
     }
    QString dircdup5 = fdir.join("/");
    dircdup5.prepend("/");
    dircdup5.append("/");
    return CheckSlash(dircdup5);
}


QString MicroQuote( QString xml )
{
    /////QString bole = "";
   QString text = xml;
   text.replace("\"","\\\"");  /* 228 ``*/
   text.replace("'","`");
   text.replace("\t"," ");
   text.replace("\n"," ");
   text.replace("\r"," ");
   return text;
}




QString KeywordGenerator( QString xml )
{
    QString stream = MicroQuote(xml);
    QStringList eachword = stream.split(" ");
    QStringList metakey;
    metakey.clear();
    for (int i=0;i<eachword.size();i++) {
        QString now = eachword.at(i);
        now = now.toLower();
        /*  && !now.contains(".")  */
        if (now.size() > 3
            && !now.contains(",")
            && !now.contains(":") 
            && !now.contains("&") 
            && !now.contains("=")
            && !now.contains("|")
            && !now.contains(")")
            && !now.contains("(")
            && !now.contains("#")
            && !now.contains("*")
            && !now.contains("-")
            && !now.contains("`")
            && !now.contains("_")
            && !now.contains("|")
            && !now.contains("\\")
            && !now.contains(";")
            && !metakey.contains(now,Qt::CaseInsensitive)) 
        {
        metakey.append(now);
        }
        if (metakey.size() > KEYWORDMAX_NUMMER) {
        return metakey.join(" , ");
        }
    }
    
return metakey.join(" , ");  
}




protected:
private:
   QString currentdir;
 void Load_Connector()
{
currentdir = QDir::currentPath();   /* remember current path on start! */
}
signals:
public slots:

};






              
/*
QDir::homePath()
 QString( "%1/.%2/" ).arg(QDir::homePath(),_PROGRAM_SHORT_NAME)
 QString(setter.value("LastDir").toString())
 Cache(IMAGE_PASTE_CACHE)
*/
/* typedef  */


typedef enum
{  
  D_FLOAT_DIV = 10,
  D_BASE_DIV,
  D_FLOAT_IMAGE,
  D_ROOT,
  D_UNCOOL
} DOCUMENT_TYP;


typedef enum
{  
  M_EDIT = 1,
  M_BROWSER,
  M_MOVE,
  M_PRINT,
  M_DISPLAY
} PAGE_MODUS;


typedef enum
{  
  TAG_NOT_KNOW = 404,
  PAGE_SETUP, /* fo:simple-page-master  405 */
  BLOCK_TAG,    /* fo:block  406*/
  TABLE_TAG,  /* fo:table 407*/
  TABLE_FOOTER, /* table-footer  408*/
  TABLE_HEADER, /* table-header 409*/
  TABLE_BODY, /* fo:table-body 410*/
  TABLE_COL, /* fo:table-column 411*/
  TABLE_ROW,   /* fo:table-row 412*/
  TABLE_CELL, /* fo:table-cell 413*/
  BLOCK_CONTAINER,  /* fo:block-container   floating layer 414*/ 
  INLINE_STYLE,  /* fo:inline 415*/
  LINK_DOC,  /* fo:basic-link 416*/
  IMAGE_SRC, /* fo:external-graphic / fo:internal-graphic  all supported qt4.4 image + tif 417*/
  IMAGE_INLINE,  /* fo:instream-foreign-object  svg inline only svg image grep 418*/
  LIST_BLOCK,   /* fo:list-block  ul/ol 419*/
  LIST_ITEM,   /* fo:list-item  li 420*/
  LIST_BODY,   /* fo:list-item-body 421*/
  LIST_LABEL,   /* fo:list-item-label  422*/
  FIRST_LAST_TAG      /* fo:root 423*/
} FOTAGENUM;





/* check if a int or float nummer */
static inline bool is_numeric(QString incomming)
{
    incomming.replace(QString(" "), QString("")); /* trimm */
    QString str2 = incomming;
    bool ok; 
    str2.toFloat(&ok); 
return ok;
}


static inline qreal UnitInt( const QString datain )
{
   QString ctmp = datain;
  QString data = ctmp.replace(" ","").trimmed();
    
    
    
  //////////qDebug() << "### request unit data->" << datain << " size->" << datain.size();    
  #define MM_TO_POINT(mm) ((mm)*2.83465058)
  #define CM_TO_POINT(cm) ((cm)*28.3465058)
  #define DM_TO_POINT(dm) ((dm)*283.465058)
  #define INCH_TO_POINT(inch) ((inch)*72.0)
  #define PI_TO_POINT(pi) ((pi)*12)
  #define DD_TO_POINT(dd) ((dd)*154.08124)
  #define CC_TO_POINT(cc) ((cc)*12.840103)
  qreal points = 0;
  if (data.size() < 1) {
  return points;
  }
  
  if ( data.endsWith( "pt" ) ) {
    points = data.left( data.length() - 2 ).toDouble();
  } else if ( data.endsWith( "cm" ) ) {
    double value = data.left( data.length() - 2 ).toDouble();
    points = CM_TO_POINT( value );
  } else if ( data.endsWith( "em" ) ) {
    points = data.left( data.length() - 2 ).toDouble();
  } else if ( data.endsWith( "mm" ) ) {
    double value = data.left( data.length() - 2 ).toDouble();
    points = MM_TO_POINT( value );
  } else if ( data.endsWith( "dm" ) ) {
    double value = data.left( data.length() - 2 ).toDouble();
    points = DM_TO_POINT( value );
  } else if ( data.endsWith( "in" ) ) {
    double value = data.left( data.length() - 2 ).toDouble();
    points = INCH_TO_POINT( value );
  } else if ( data.endsWith( "inch" ) ) {
    double value = data.left( data.length() - 4 ).toDouble();
    points = INCH_TO_POINT( value );
  } else if ( data.endsWith( "pi" ) ) {
    double value = data.left( data.length() - 4 ).toDouble();
    points = PI_TO_POINT( value );
  } else if ( data.endsWith( "dd" ) ) {
    double value = data.left( data.length() - 4 ).toDouble();
    points = DD_TO_POINT( value );
  } else if ( data.endsWith( "cc" ) ) {
    double value = data.left( data.length() - 4 ).toDouble();
    points = CC_TO_POINT( value );
  } else {
    points = 0;
    ////////qDebug( "unknown unit %s", qPrintable( datain ) );
    QMessageBox::warning(0,"Unit converter",QString("unknown Unit \"%1\"").arg(datain));
  }

  return points;
}



static inline QString DesktopFile( QString fullFileName )
{
    if (fullFileName.startsWith("http://", Qt::CaseInsensitive) or 
        fullFileName.startsWith("https://", Qt::CaseInsensitive) or
        fullFileName.startsWith("ftp://", Qt::CaseInsensitive) or
        fullFileName.startsWith("news://", Qt::CaseInsensitive) or
        fullFileName.startsWith("mailto:", Qt::CaseInsensitive) or
        fullFileName.startsWith("webdav://", Qt::CaseInsensitive)  )
       { 
         return fullFileName;
       } else {
         return fullFileName.prepend("file:///");  
       }
}



/* grep nummer on [77] */
static inline int  BraketNummer( QString braket )
{
    int esanummer = 0;
    if (braket.startsWith("[")) {
       braket.replace(QString("["), QString("")); 
       int zool = braket.indexOf("]",0); 
           if (zool > 0) {
              QString   xid = braket.left(zool);  
               if (is_numeric(xid)) {
                      bool ok; 
                      esanummer = xid.toInt(&ok);
               }
           }
    }
return esanummer;
}


static inline  QImage GreyScale( QImage income )
{
    
    QImage base =  income.convertToFormat(QImage::Format_RGB32);
    for (int y = 0; y < base.height(); ++y) {
             for (int x = 0; x < base.width(); ++x) {
                 int pixel = base.pixel(x, y);
                 int gray = qGray(pixel);
                 int alpha = qAlpha(pixel);
                 base.setPixel(x, y, qRgba(gray, gray, gray, alpha));
             }
         }
         
    return base;
}







static inline bool Cache()
{
     QDir dira(WORK_CACHEDIR);
    if ( dira.mkpath(WORK_CACHEDIR) ) {
    return true;
    } else {
    return false;
    }
}

static inline bool Cache( const QString dirpath )
{
     QDir dira(dirpath);
    if ( dira.mkpath(dirpath) ) {
    return true;
    } else {
    return false;
    }
}


/* remove a file */
static inline bool qt4unlink(QString fullFileName)
{
    if (fullFileName.size() > 0) {
    QFile f( fullFileName );
	if ( f.exists(fullFileName) ) {
       if (f.remove()) {
        return true;
       }
	}
    }
return false;
}

/* remove dir recursive */
static inline void DownDir_RM(const QString d)
{
   QDir dir(d);
   //////SqlLog("order to delete dir:"+d+" ");
   if (dir.exists())
   {
      const QFileInfoList list = dir.entryInfoList();
      QFileInfo fi;
      for (int l = 0; l < list.size(); l++)
      {
         fi = list.at(l);
         if (fi.isDir() && fi.fileName() != "." && fi.fileName() != "..")
            DownDir_RM(fi.absoluteFilePath());
         else if (fi.isFile())
         {
            qt4unlink(fi.absoluteFilePath());
            ///////if (!ret) {
               ////////SqlLog("Can't remove: " + fi.absoluteFilePath() + " (write-protect?)");
         } 
        
      }
     /////// SqlLog("Remove: " + d + " ");
      dir.rmdir(d);
      
   }
} 




/* check if a file exist alert dons say true if a zero byte file!  */
static inline bool is_file(QString fullFileName)
{
    if (!fullFileName.size() > 3) {
      return false;  
    }
    QFile f( fullFileName );
	if ( f.exists(fullFileName) ) {
    return true;  
	} else {
	return false;
    }
}

/* remove a file */
static inline bool qt_unlink(QString fullFileName)
{
    if (fullFileName.size() > 0) {
    QFile f( fullFileName );
	if ( f.exists(fullFileName) ) {
       if (f.remove()) {
        return true;
       }
	}
    }
return false;
}



/* copy file from a to b ... if dir not exist make it ...*/
static inline bool Copy_To(QString inputfile, QString outfile)
{
    bool actioncpy = false;
    QString ultimacartellaaperta = outfile.left(outfile.lastIndexOf("/"))+"/";
    QDir dira(ultimacartellaaperta);
    if ( dira.mkpath(ultimacartellaaperta) ) { } else {
    return actioncpy;
    }
    if (is_file(inputfile)) {
           qt_unlink(outfile);
           QFile Imaged(inputfile); 
               if (Imaged.copy(outfile)) {
                   actioncpy = true; 
                }
    }
return actioncpy;
}



static inline bool  image_extension( QString nametomake )
{
    bool fanny = false;
    QString na;
    na = nametomake.toLower();
    if ( na.endsWith(".png") || na.endsWith(".jpeg") || na.endsWith(".jpg") || na.endsWith(".gif") ) {
     fanny = true;   
    }
return fanny;
}


//
#endif // BASE_MODUL_H

